package edu.temple.mobile.displayClasses;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import edu.temple.mobile.R;
import edu.temple.mobile.SEPTripActivity;
import edu.temple.mobile.TransitViewActivity;
import edu.temple.mobile.adapters.TrolleyRoutesAdapter;
import edu.temple.mobile.helpers.WebService;
import edu.temple.mobile.objectClasses.TrolleyRoutes;

public class TrolleyRoutesDisplayActivity extends Activity {
	private ImageButton homeButton;
	private TextView title;
	 /** Called when the activity is first created. */
		//ListView that will hold our items references back to main.xml
		ListView lstTest;
		//Array Adapter that will hold our ArrayList and display the items on the ListView
		TrolleyRoutesAdapter arrayAdapter;
		AlertDialog alertDialog;
		Intent intent;
		TrolleyRoutes al;

		//List that will  host our items and allow us to modify that array adapter
		ArrayList<TrolleyRoutes> alrts=null;
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.listview);
	        
	        /**Home button */
			homeButton = (ImageButton) findViewById(R.id.actionLogoIcon);
			homeButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					
					Intent intent = new Intent(TrolleyRoutesDisplayActivity.this,SEPTripActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		            startActivity(intent);
				}
			});
			title = (TextView) findViewById(R.id.title);
			title.setText(getString(R.string.trolley) + " " + getString(R.string.routes));
	        
	        //Initialize ListView
	        lstTest= (ListView)findViewById(R.id.lstText);
	        int[] colors = {0xFF0000FF, 0xFFFFFFFF, 0xFFFF0000}; // red for the example
	        lstTest.setDivider(new GradientDrawable(Orientation.LEFT_RIGHT, colors));
	        lstTest.setDividerHeight(3);

	         //Initialize our ArrayList
	        alrts = new ArrayList<TrolleyRoutes>();
	        //Initialize our array adapter notice how it references the listitems.xml layout
	        arrayAdapter = new TrolleyRoutesAdapter(TrolleyRoutesDisplayActivity.this, R.layout.listitems,alrts);

	        //Set the above adapter as the adapter of choice for our list
	        lstTest.setAdapter(arrayAdapter);
	        lstTest.setTextFilterEnabled(true);

	        lstTest.setOnItemClickListener(new OnItemClickListener() {
	        	@Override
	        	public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) {
	        		//lstTest.getItemAtPosition(arg2);
	        		//Object d = lstTest.getItemAtPosition(arg2);
	        		
	        	// TODO Auto-generated method stub
	        		String rId = "";
	        		int id = alrts.get(arg2).route_short_name;
	        		rId += id;
	        		
	        		intent = new Intent(TrolleyRoutesDisplayActivity.this, TransitViewActivity.class);
	        		intent.putExtra("shortName", rId);
	        		intent.putExtra("vehicle", "Trolley");
					TrolleyRoutesDisplayActivity.this.startActivity(intent);
	        		
	        		//Toast.makeText(getApplicationContext(), "You have selected "  + id, Toast.LENGTH_LONG).show();
	        		Log.d("TrolleyRoutes", "Item clicked " + alrts.get(arg2).route_short_name);
	        		

	        	}
	        	});
	        
	        class getJSONTask extends AsyncTask<String, Void, String>{
	        	private ProgressDialog dialog;
				protected void onPreExecute(){
					dialog = ProgressDialog.show(TrolleyRoutesDisplayActivity.this, "", 
	                        "Loading Trolley Routes. Please wait...", true);
				}
				
				protected String doInBackground(String... webServiceURL){
					//Instantiate the Web Service Class with he URL of the web service not that you must pass
			        WebService webService = new WebService(webServiceURL[0]);

			        //Pass the parameters if needed , if not then pass dummy one as follows
					Map<String, String> params = new HashMap<String, String>();
					params.put("", "");
					String response = webService.webGet("", params);//Network on Main Thread Exception thrown
					return response;
				}
				
				protected void onPostExecute(String response){
					dialog.dismiss();
					try
					{
						//Parse Response into our object
						Type collectionType = new TypeToken<ArrayList<TrolleyRoutes>>(){}.getType();

						//JSON expects an list so can't use our ArrayList from the lstart
						List<TrolleyRoutes> lst= new Gson().fromJson(response, collectionType);

						//Now that we have that list lets add it to the ArrayList which will hold our items.
						for(TrolleyRoutes l : lst)
						{
							alrts.add(l);
						}

						//Since we've modified the arrayList we now need to notify the adapter that
						//its data has changed so that it updates the UI
						//Remove the Norristown High Speed Line from the list since TransitView is not offered for this route.
						alrts.remove(9);
						arrayAdapter.notifyDataSetChanged();
					}
					catch(Exception e)
					{
						Log.e("Error:", ""+e.getMessage());
					}
				}
			}
	      //Redownloads on orientation change
			new getJSONTask().execute("http://cis-linux2.temple.edu/~tua49072/trolley_routes2.php");

			
		    }
	    
	}